using System;
using System.Text;
using System.Collections;
using System.Collections.Generic;
using System.Windows.Forms;
using System.Data;

using WP.Commons;
using WP.DB;
using WP.MF.DataAccess;
using WP.MF.DataEntity;


namespace WP.MF.BusinessRule
{
    public class MMiscSwitchBRL : RuleBase
    {
        public MMiscSwitchBRL()
		{
			//
			// TODO: Add constructor logic here
			//
		}
        #region Insert MMiscSwitch Valid
        public bool InsertValid(DBAccess dBAccess, MMiscSwitchDEL mMiscSwitchDEL)
        {
            bool bReturn = true;
            SysVar.ErrorMessage.Clear();
            string strErrPrompt = string.Empty;

            DataView dvwCheck = dBAccess.GetDataTable("select * from mnamedict where NeedCheck=1 and tablename='" + MMiscSwitchDEL.TABLENAME_MMISCSWITCH + "'").DefaultView;

            foreach (DataRowView drw in dvwCheck)
            {
                if (!FieldCheck(dBAccess, mMiscSwitchDEL.Tables[MMiscSwitchDEL.TABLENAME_MMISCSWITCH].Rows[0], drw["FieldName"].ToString(), ref  strErrPrompt, FormStatus.AddNew))
                {
                    if (SysVar.ErrorMessage.Count == 0)
                    {
                        SysVar.ErrorMessage.Add(new ErrInfo(strErrPrompt, drw["FieldName"].ToString().TrimEnd()));
                    }

                    bReturn = false;
                    break;
                }
            }
            return bReturn;
        }
        #endregion

        #region Update MMiscSwitch Valid
        public bool UpdateValid(DBAccess dBAccess, MMiscSwitchDEL mMiscSwitchDEL)
        {
            bool bReturn = true;
            SysVar.ErrorMessage.Clear();
            string strErrPrompt = string.Empty;
            if (IsExistedAndNotChanged(dBAccess, mMiscSwitchDEL.Tables[MMiscSwitchDEL.TABLENAME_MMISCSWITCH]))
            {
                DataView dvwCheck = dBAccess.GetDataTable("select * from mnamedict where NeedCheck=1 and tablename='" + MMiscSwitchDEL.TABLENAME_MMISCSWITCH + "'").DefaultView;

                foreach (DataRowView drw in dvwCheck)
                {
                    if (!FieldCheck(dBAccess, mMiscSwitchDEL.Tables[MMiscSwitchDEL.TABLENAME_MMISCSWITCH].Rows[0], drw["FieldName"].ToString(), ref  strErrPrompt, FormStatus.Update))
                    {
                        bReturn = false;
                        if (SysVar.ErrorMessage.Count == 0)
                        {
                            SysVar.ErrorMessage.Add(new ErrInfo(strErrPrompt, drw["FieldName"].ToString()));
                        }
                        break;
                    }
                }
            }
            else
            {
                bReturn = false;
            }
            return bReturn;
        }

        #endregion

        #region Delete MMiscSwitch Valid
        public bool DeleteValid(DBAccess dBAccess, string strRecId, byte[] btOldRecStamp)
        {
            SysVar.ErrorMessage.Clear();

            //the error was msgboxed, so just exit here
            if (!base.IsExistedAndNotChanged(dBAccess, "MMiscSwitch", strRecId, btOldRecStamp))
            {
                return false;
            }

            if (MsgBoxEx.Show(Msg.Select("Are you sure to delete this Switch?", DataFunctions.GetMsg(this.GetType().Name, "MSG_DeleteThisSwitch")), SysVar.ConfirmTitle, MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2) == DialogResult.No)
            {
                return false;
            }
            return true;
        }

        #endregion

        public bool FieldCheck(DBAccess dBAccess, DataRow dr, string strFieldName, ref string strErrPrompt, FormStatus formStatus)
        {
            strErrPrompt = "";
            bool blnExistsField = false;
            for (int i = 0; i < dr.Table.Columns.Count; i++)
            {
                if (dr.Table.Columns[i].Caption.ToUpper().Trim() == strFieldName.Trim().ToUpper())
                {
                    blnExistsField = true;
                    break;
                }
            }
            if (!blnExistsField) return true; 
            string strFieldValue = CvtFunc.ToString(dr[strFieldName.Trim()]);

            switch (strFieldName.ToUpper().Trim())
            {
                #region SWITCHNAME
                case "SWITCHNAME":
                    if (formStatus == FormStatus.AddNew)
                    {
                        if (DataFunctions.CheckRecordExist(dBAccess, "Mmiscswitch", strFieldValue, strFieldName))
                        {
                            strErrPrompt =Msg.Select("Switch Name already on file!", DataFunctions.GetMsg(this.GetType().Name, "MSG_SwitchNameAlreadyOnFile"));
                            return false;
                        }
                        else
                            return true;
                    }
                    else
                        return true;
                #endregion

                #region SWITCHVALUE
                case "SWITCHVALUE":
                    if (formStatus == FormStatus.Update)
                    {
                        if (!this.CheckValue(dr, ref strErrPrompt))
                        {
                            return false;
                        }
                    }
                    return true;
                #endregion

                #region SWITCHNO
                case "SWITCHNO":
                    if (formStatus == FormStatus.AddNew)
                        return RuleBase.FieldValueCheckOne(dBAccess, strFieldValue, "Mmiscswitch", strFieldName, ref strErrPrompt);
                    else
                        return true;
                #endregion
                default:
                    return RuleBase.FieldValueCheckOne(dBAccess, strFieldValue, "MMiscSwitch", strFieldName, ref strErrPrompt);
            }
        }

        private bool CheckValue(DataRow dr,ref string strErrPrompt)
        {
            string strValue = string.Empty;
            string strType = string.Empty;
            string strcheckString = string.Empty;
            int intMaxLen = -1;
            string strFieldType = string.Empty;
            string strCheckItem = string.Empty;

            strValue = dr["SwitchValue"].ToString().TrimEnd();
            strType = dr["Type"].ToString().TrimEnd();
            intMaxLen = CvtFunc.ToInt(dr["MaxLength"].ToString());
            if (intMaxLen == 0)
                intMaxLen = 10;
            strcheckString = dr["CheckString"].ToString().TrimEnd();
            strFieldType = "C";

            //1--check type
            if (strType.TrimEnd().ToUpper() == "DATE")
            {
                strFieldType = "D";
                if (strValue.TrimEnd() != "" && !BaseFunctions.IsDate(strValue.TrimEnd()))
                {

                    strErrPrompt = Msg.Select("The value must be date type..", DataFunctions.GetMsg(this.GetType().Name, "MSG_ValueMustBeDateType"));
                    return false;
                }
            }

            if (strType.TrimEnd().ToUpper() == "NUMERIC")
            {
                strFieldType = "N";
                if (!BaseFunctions.IsNumeric(strValue.TrimEnd()))
                {
                    strErrPrompt = Msg.Select("The value must be numeric type.", DataFunctions.GetMsg(this.GetType().Name, "MSG_ValueMustBeNumericType"));
                    return false;
                }
            }
            //2--check Length
            if (strType.TrimEnd().ToUpper() == "CHAR")
            {
                if (strValue.Length > intMaxLen)
                {
                    strErrPrompt = Msg.Select("The value cannot be greater than " + intMaxLen.ToString() + " characters.", DataFunctions.GetMsg(this.GetType().Name, "MSG_ValueCanNotBeGreaterThan", new string[] { intMaxLen.ToString() }));
                    return false;
                }
            }

            if (strType.TrimEnd().ToUpper() == "NUMERIC")
            {
                strValue = BaseFunctions.FormatNumeric(strValue, "N.N").TrimEnd();
                if (strValue.Length > intMaxLen)
                {
                    strErrPrompt = Msg.Select("The value cannot be greater than " + intMaxLen.ToString() + " characters.", DataFunctions.GetMsg(this.GetType().Name, "MSG_ValueCanNotBeGreaterThan", new string[] { intMaxLen.ToString() }));
                    return false;
                }
            }

            //3---Start check by rules
            //start check whether it must be exist in a table
            //int h = 1;
            //strCheckItem = GetSplitItem(h, strcheckString);

            //if (strCheckItem.Substring(0, 2) == "1.")   //Empty
            //{
            //    if (strValue.TrimEnd() == "")
            //    {
            //        MsgBoxEx.Show("Invalid value,the value can not be empty.", SysVar.WarnTitle);
            //        return false;
            //    }
            //}
            //else
            //{
            //    if (strValue.TrimEnd() == "")
            //    {
            //        return true;
            //    }
            //}

            //Do Until strCheckItem = ""
            //    If Mid(strCheckItem, 1, 2) = "3." Then
            //        strExist = Mid(strCheckItem, 3)
            //        If Len(strExist) > 0 And Len(strValue) > 0 Then
            //               strRulePart = RTrim(strExist)
            //               strRulePart = Mid(strRulePart, 2, Len(strRulePart) - 2)  'filter "(,)"
            //               j = InStr(strRulePart, ",")
            //               If j > 0 Then
            //                  strCheckTable = RTrim(Mid(strRulePart, 1, j - 1))
            //                  strCheckField = RTrim(Mid(strRulePart, j + 1))
            //                  If Not CheckRecordExist(strCheckTable, strValue, strCheckField) Then
            //                     strerrmsg = "The value not on file."
            //                     MsgBox strerrmsg, vbExclamation, SysVar.WarnTitle
            //                     Exit Function
            //                  End If
            //               End If
            //        End If
            //    ElseIf Mid(strCheckItem, 1, 2) = "2." Then
            //        strRange = Mid(strCheckItem, 3)
            //        If Len(strRange) > 0 And Len(strValue) > 0 Then
            //               strRulePart = RTrim(strRange)
            //               strPartChar = ""
            //               blnInRange = False
            //               For j = 1 To Len(strRulePart)
            //                   Select Case Mid(strRulePart, j, 1)
            //                   Case "(", "'", "[", "]"
            //                   Case ",", ")"
            //                        If InStr(strPartChar, ":") > 0 Then
            //                               If strFieldType = "N" Then
            //                                    If Val(strValue) >= Val(Mid(strPartChar, 1, InStr(strPartChar, ":") - 1)) And Val(strValue) <= Val(Mid(strPartChar, InStr(strPartChar, ":") + 1)) Then
            //                                       blnInRange = True
            //                                       Exit For
            //                                    End If
            //                               Else
            //                                    If IsNumeric(Mid(strPartChar, 1, InStr(strPartChar, ":") - 1)) And IsNumeric(Mid(strPartChar, InStr(strPartChar, ":") + 1)) Then
            //                                       If IsNumeric(strValue) Then
            //                                            If Val(strValue) >= Val(Mid(strPartChar, 1, InStr(strPartChar, ":") - 1)) And Val(strValue) <= Val(Mid(strPartChar, InStr(strPartChar, ":") + 1)) Then
            //                                                blnInRange = True
            //                                                Exit For
            //                                            End If
            //                                       End If
            //                                    Else
            //                                       If strValue >= Mid(strPartChar, 1, InStr(strPartChar, ":") - 1) And strValue <= Mid(strPartChar, InStr(strPartChar, ":") + 1) Then
            //                                          blnInRange = True
            //                                          Exit For
            //                                       End If
            //                                    End If
            //                              End If
            //                        Else
            //                            If strValue = strPartChar Then
            //                               blnInRange = True
            //                               Exit For
            //                            End If
            //                        End If
            //                        strPartChar = ""
            //                   Case ":"
            //                        strPartChar = strPartChar & Mid(strRulePart, j, 1)
            //                   Case Else
            //                        strPartChar = strPartChar & Mid(strRulePart, j, 1)
            //                   End Select
            //               Next
            //               If Not blnInRange Then
            //                   strerrmsg = "The value is not within the range of correct items."
            //                   MsgBox strerrmsg, vbExclamation, SysVar.WarnTitle
            //                   Exit Function
            //               End If
            //        End If
            //    End If
            //    h = h + 1
            //    strCheckItem = getSplitItem(h, strcheckString)
            //Loop
            //CheckValue = True 
            return true;
        }

        private string GetSplitItem(int h, string strcheckString, string strSplitChar)
        {
            //Dim i As Integer
            //Dim j As Integer
            //Dim k As Integer
            //i = 1
            //k = 0
            //While k < h
            //  j = i
            //  If InStr(i, strcheckString, strSplitChar) > 0 Then
            //     k = k + 1
            //     i = InStr(i, strcheckString, strSplitChar) + Len(strSplitChar)
            //  Else
            //     If k + 1 = h Then
            //        getSplitItem = Trim(Mid(strcheckString, i))
            //        Exit Function
            //     Else
            //        getSplitItem = ""
            //        Exit Function
            //     End If
            //  End If
            //Wend
            //getSplitItem = Trim(Mid(strcheckString, j, i - Len(strSplitChar) - j))
            return "";
        }

        private string GetSplitItem(int h, string strcheckString)
        {
            return this.GetSplitItem(h, strcheckString, "&&");
        }
    }
}
